<script setup>
import {Delete, Edit, Plus} from "@element-plus/icons-vue";
import {onMounted, ref, watchEffect} from "vue";
import { useUserInfoStore } from "@/stores/userInfo";// 已有的引入
import {
  orderDelete,
  orderInsert,
  orderList,
  orderUpdate,
} from "@/api/order";
import {ElMessage, ElMessageBox} from "element-plus";
import dayjs from "dayjs";
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(0)//总条数
const pageSize = ref(5)//每页条数
const orderListDate = ref([])
const dialogVisible = ref(false)
const titleName = ref('')
// 初始化时获取用户信息
const userInfoStore = useUserInfoStore();
// 获取登录用户的 ID（假设存储字段为 id 或 merchantId，根据实际情况修改）
const currentId = ref('');
const currentMerchantId = ref(''); // 如果是商家，可能存储的是 merchantId

onMounted(()=>{
  // 从全局状态中获取用户 ID
  currentId.value = userInfoStore.userInfo.id;
  console.log(currentId.value)
  // 初始化时调用订单列表接口（此时已能获取到用户 ID）
  getOrderList();
})

// 用户添加、编辑表单数据模型
const formData = ref({
  id: '',
  userId: '',
  carId: '',
  merchantId:'',
  startTime:'',
  endTime:'',
  actualStartTime:'',
  actualEndTime: '',
  rentDays: '',
  dailyRent: '',
  estimatedTotalAmount: '',
  overtimeFee: '',
  damageFee: '',
  finalAmount: '',
  status: '',

})
const form = ref(null)
const formLabelWidth = '140px'
// 获取用户列表
const getOrderList = ()=>{
  const params = {
    params:{
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      userId: formData.value.userId,
      carId: formData.value.carId,
      merchantId:currentId.value,
      status: formData.value.status,
  }
  }
  console.log(params)
  orderList(params).then(res=>{
    orderListDate.value = res.data.records
    console.log(res.data.records)
    total.value = res.data.count
  })
}
const resetParams = ()=>{
  formData.value.userId = ''
  formData.value.carId = ''
  formData.value.status = ''
  getOrderList()
}
// 当每页条数发生了变化，会调用
const handleSizeChange = (val) => {
  pageSize.value = val
  getOrderList()
}
// 当当前页面发生变化，会调用
const handleCurrentChange = (val) => {
  pageNum.value = val
  getOrderList()
}
// 删除用户
const deleteById = (id) => {
  ElMessageBox.confirm(
      '是否确认删除，删除后不可恢复',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        orderDelete({id: id}).then(res=>{
          if (res.code === 200) {
            ElMessage.success('删除成功')
            getOrderList()
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

// 用户添加打开dialog
const showAddDialog = (title) => {
  dialogVisible.value = true
  titleName.value = title
  //添加用户前清空绑定数据
  formData.value = {
    id: '',
    userId: '',
    carId: '',
    merchantId:'',
    startTime:'',
    endTime:'',
    actualStartTime:'',
    actualEndTime: '',
    rentDays: '',
    dailyRent: '',
    estimatedTotalAmount: '',
    overtimeFee: '',
    damageFee: '',
    finalAmount: '',
    status: '',
  }
  // 重置校验状态
  if (form.value) {
    form.value.resetFields();
  }
}
//定义添加表单校验
const rules = {
  userId: [
    { required: true, message: '请输入用户id', trigger: 'blur' },
  ],
  carId: [
    { required: true, message: '请输入车辆id', trigger: 'blur' },
  ],
  merchantId: [
    { required: true, message: '请输入商家id', trigger: 'blur' },
  ],
  startTime: [
    { required: true, message: '预计开始时间', trigger: 'blur' },
  ],
  endTime: [
    { required: true, message: '预计结束时间', trigger: 'blur' },

  ],
  actualStartTime: [
    { required: true, message: '实际开始时间', trigger: 'blur' },
  ],
  actualEndTime: [
    { required: true, message: '实际结束时间', trigger: 'blur' },
  ],
  rentDays: [
    { required: true, message: '请输入租车时间', trigger: 'blur' },
  ],
  dailyRent: [
    { required: true, message: '请输入日租金', trigger: 'blur' },
  ],
  overtimeFee: [
    { required: true, message: '请输入超时费用', trigger: 'blur' },
  ],
  damageFee: [
    { required: true, message: '请输入损坏费用', trigger: 'blur' },
  ],
  estimatedTotalAmount: [
    { required: true, message: '预计总费用', trigger: 'blur' },
  ],
  finalAmount: [
    { required: true, message: '实际总费用', trigger: 'blur' },
  ],
   status: [
    { required: true, message: '请选择订单状态', trigger: 'blur' },
  ],
}
// 用户添加
const addUser = () => {
  form.value.validate((valid) => {
    if (valid) {
      formData.value.startTime=dayjs(formData.value.startTime).format('YYYY-MM-DD HH:mm:ss')
      formData.value.endTime=dayjs(formData.value.endTime).format('YYYY-MM-DD HH:mm:ss')
      formData.value.actualStartTime=dayjs(formData.value.actualStartTime).format('YYYY-MM-DD HH:mm:ss')
      formData.value.actualEndTime=dayjs(formData.value.actualEndTime).format('YYYY-MM-DD HH:mm:ss')
      orderInsert(formData.value).then(res=>{
        if (res.code === 200) {
          ElMessage.success('添加成功')
          dialogVisible.value = false
          resetParams()
        }
      })
    }
  })
}
// 打开编辑dialog
const showEditDialog=(row,title) => {
  dialogVisible.value = true
  titleName.value = title
  formData.value = {
    ...row
  }
 //  console.log(Number(row.actualEndTimeStr))
 //  console.log(Number(row.dailyRent))
 //  console.log(Number(row.actualStartTimeStr))
 // formData.value.finalAmount = (Number(row.actualEndTime )- Number(row.actualStartTime))*Number(row.dailyRent)
  // 重置校验状态
  if (form.value) {
    form.value.resetFields();
  }
}
// 更新用户
const eidetUser = () => {
  formData.value.startTime=dayjs(formData.value.startTime).format('YYYY-MM-DD HH:mm:ss')
  formData.value.endTime=dayjs(formData.value.endTime).format('YYYY-MM-DD HH:mm:ss')
  formData.value.actualStartTime=dayjs(formData.value.actualStartTime).format('YYYY-MM-DD HH:mm:ss')
  formData.value.actualEndTime=dayjs(formData.value.actualEndTime).format('YYYY-MM-DD HH:mm:ss')                                      //打印
  orderUpdate(formData.value).then(res=>{
    if (res.code === 200) {
      ElMessage.success('更新成功')
      dialogVisible.value = false
      resetParams()
    }
  })
}
const dialogVisibleClose=()=>{
  // 重置校验状态
  if (form.value) {
    form.value.resetFields();
  }
  dialogVisible.value = false
  }
// 表单校验
//1. 定义类别映射关系（替代过滤器）
// 订单状态与用户统一

const typeMap = {
  0: "待取车",
  2: "已取车",
  3: "已还车",
  4: "待支付",
  5: "订单完成",
};
// 2. 转换类别ID为名称的函数（替代过滤器）
const getTypeName = (typeId) => {
  // 如果typeId不存在或未匹配，返回"未知类别"
  return typeMap[typeId] || "未知类别";
};
// 3. 定义标签类型的样式（可选，用于美化显示）
const getTagType = (typeId) => {
  // 根据不同类别ID返回不同标签样式
  const typeStyles = ["success", "info", "warning", "danger", "primary"];
  // 取模避免数组越界
  return typeStyles[(typeId - 1) % typeStyles.length];
};
</script>
<template>
  <el-card class="page-container">
<!--   头   -->
    <template #header>
      <div class="header">
        <span>商家-订单-管理</span>
<!--        <div class="extra">-->
<!--          <el-button type="primary" @click="showAddDialog('添加订单')">添加订单</el-button>-->
<!--        </div>-->
      </div>
    </template>
    <!-- 搜索表单 -->
      <el-form >
        <el-row>
          <el-col :span="6">
            <el-form-item label="用户ID：">
              <el-input v-model="formData.userId" placeholder="请输入用户ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆ID：">
              <el-input v-model="formData.carId" placeholder="请输入车辆ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租赁状态：">
              <el-select v-model="formData.status" placeholder="请选择租赁状态">
                <el-option label="待取车" :value="0"></el-option>
                <el-option label="已取车" :value="2"></el-option>
                <el-option label="已还车" :value="3"></el-option>
                <el-option label="待支付" :value="4"></el-option>
                <el-option label="订单完成" :value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="getOrderList">搜索</el-button>
              <el-button @click="resetParams">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    <!-- 订单列表 -->
    <el-table :data="orderListDate" style="width: 100%">
      <el-table-column label="用户id" prop="userId"></el-table-column>
      <el-table-column label="车辆ID" prop="carId"></el-table-column>
      <el-table-column label="预计取车时间" prop="startTimeStr"></el-table-column>//原本显示时间戳，在后端entity添加了转换方法
      <el-table-column label="预计还车时间" prop="endTimeStr"></el-table-column>
      <el-table-column label="实际取车时间" prop="actualStartTimeStr"></el-table-column>
      <el-table-column label="实际还车时间" prop="actualEndTimeStr"></el-table-column>
      <el-table-column label="预计租赁天数" prop="rentDays"></el-table-column>
      <el-table-column label="日租金" prop="dailyRent"></el-table-column>
      <el-table-column label="预计总金额" prop="estimatedTotalAmount"></el-table-column>
      <el-table-column label="最终结算金额" prop="finalAmount"></el-table-column>
      <el-table-column label="订单状态" prop="status">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.status)">
            {{ getTypeName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showEditDialog(row,'编辑订单')"></el-button>
          <el-button :disabled="userInfoStore.userInfo.id===row.id" :icon="Delete" circle plain type="danger" @click="deleteById(row.id)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>

<!--    添加用户对话框-->
    <el-dialog v-model="dialogVisible" :title="titleName" width="800">
      <el-form ref="form" :rules="rules" :model="formData" style="max-width: 800px" label-width="auto">
        <el-row>
          <el-col :span="1">
          </el-col>
          <el-col :span="10">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="formData.userId" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="车辆ID" prop="carId">
              <el-input v-model="formData.carId" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="1">
          </el-col>
          <el-col :span="10">
            <el-form-item label="商家ID" prop="merchantId">
              <el-input v-model="formData.merchantId" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="日租金" prop="dailyRent">
              <el-input v-model="formData.dailyRent" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="1">
          </el-col>
          <el-col :span="10">
            <el-form-item label="预计取车时间" prop="startTime">
              <el-date-picker v-model="formData.startTime" type="date" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="预计还车时间" prop="endTime">
              <el-date-picker v-model="formData.endTime" type="date" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="1">
          </el-col>
          <el-col :span="10">
            <el-form-item label="实际取车时间" prop="actualStartTime" >
              <el-date-picker v-model="formData.actualStartTime" type="date" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="实际还车时间" prop="actualEndTime" >
              <el-date-picker v-model="formData.actualEndTime" type="date" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="1">
          </el-col>
          <el-col :span="10">
            <el-form-item label="预计租赁天数" prop="rentDays" >
              <el-input v-model="formData.rentDays"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="预计总金额" prop="estimatedTotalAmount" >
              <el-input v-model="formData.estimatedTotalAmount"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="1">
          </el-col>
          <el-col :span="10">
            <el-form-item label="最终结算金额" prop="finalAmount" >
              <el-input v-model="formData.finalAmount"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="订单状态" prop="status" >
              <el-select v-model="formData.status" placeholder="请选择">
                <el-option label="待取车" :value="0"></el-option>
                <el-option label="已取车" :value="2"></el-option>
                <el-option label="已还车" :value="3"></el-option>
                <el-option label="待支付" :value="4"></el-option>
                <el-option label="订单完成" :value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibleClose">取消</el-button>
          <el-button type="primary" @click="titleName==='添加订单'? addUser():eidetUser()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>
</template>

<style scoped lang="scss">
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>